﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;

namespace FriendsNearby.Services
{
    public static class TextHelper
    {
        /// <summary>
        /// Compute a pluralization of this string.
        /// Supports:
        /// ... [Number] friend ...
        /// ... [Number] person ...
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Pluralize(this string str)
        {
            str = Regex.Replace(str, @"(^|\D)0 friend($|\W)", "$1no friends$2");
            str = Regex.Replace(str, @"(^|\D)(?!1 friend)(\d+) friend($|\W)", "$1$2 friends$3");

            str = Regex.Replace(str, @"(^|\D)0 person($|\W)", "$1no people$2");            
            str = Regex.Replace(str, @"(^|\D)(?!1 person)(\d+) person($|\W)", "$1$2 people$3");            

            return str;
        }

        public static string FormatDateTimeRelativeToNow(DateTime dateTime)
        {
            TimeSpan relativeDateTime = DateTime.Now.Subtract(dateTime);
            if (relativeDateTime.TotalMinutes <= 1) return "now";
            if (relativeDateTime.TotalHours <= 1) return string.Format("{0:##} minutes ago", relativeDateTime.TotalMinutes);
            if (relativeDateTime.TotalDays <= 1) return string.Format("{0:##} hours ago", relativeDateTime.TotalHours);
            if (relativeDateTime.TotalDays <= 14) return string.Format("{0:##} days ago", relativeDateTime.TotalDays);
            if (relativeDateTime.TotalDays <= 30) return string.Format("{0:##} weeks ago", relativeDateTime.TotalDays / 7);
            if (relativeDateTime.TotalDays <= 365) return string.Format("{0:##} months ago", relativeDateTime.TotalDays / 30);
            return string.Format("{0:##} years ago", relativeDateTime.TotalDays / 364);
        }

        public static string FormatDateTimeAsUtc(DateTime dateTime)
        {
            var dateTimeInUtc = dateTime.ToUniversalTime();
            return string.Format("{0} UTC", dateTimeInUtc.ToString("HH:mm d MMM yyyy", CultureInfo.InvariantCulture));
        }
    }
}
